import elasticsearch7
from lxml import etree
from lxml.etree import tostring
import requests
import json
from elasticsearch7 import exceptions as es_exceptions
from app.config.secure import ES_URI, USERNAME, PASSWORD, PORT
from requests.auth import HTTPBasicAuth
import traceback


class DocumentEs(object):
    server = ES_URI
    headers = {'content-type': 'application/json'}
    es = elasticsearch7.Elasticsearch([ES_URI], http_auth=(USERNAME, PASSWORD), port=PORT)

    def createLocalIndex(self):
        data = {
            "settings": {
                "number_of_shards": 10,
                "number_of_replicas": 1
            },
            "mappings": {
                "properties": {
                    "user_id": {
                        "type": "keyword",
                    },
                    "content": {
                        "type": "text",
                        "analyzer": "ik_smart"
                    },
                    "filename": {
                        "type": "text",
                        "analyzer": "ik_smart"
                    },
                    "osskey": {
                        "type": "keyword"
                    },
                    "delete": {
                        "type": "keyword"
                    }
                }
            }
        }
        res = requests.put(f'{ES_URI}:{PORT}/personal_documents?pretty', headers=self.headers,
                           auth=(USERNAME, PASSWORD),
                           data=json.dumps(data))
        print(res.text)

    def deleteLocalIndex(self):
        res = requests.delete(f'{ES_URI}:{PORT}/personal_documents?pretty', headers=self.headers,
                              auth=(USERNAME, PASSWORD))
        print(res.text)

    def put_document(self, data):
        res = self.es.index(index='personal_documents', document=data, refresh=True)
        print(res)

    def get_document_id(self, osskey):
        body = {
            'query': {
                'match_phrase': {
                    'osskey': osskey
                }
            }
        }
        res = self.es.search(index='personal_documents', body=body)
        if res['hits']['total']['value'] == 1:
            return res['hits']['hits'][0]['_id']
        else:
            return None

    def delete_document(self, osskey):
        body = {
            "script": {
                "source": "ctx._source.delete = 1"
            },
            "query": {
                "term": {
                    "osskey": osskey
                }
            }
        }
        self.es.update_by_query(index='personal_documents', body=body)

    def insertIntoEs(self, info):
        body = []
        itemLength = len(info['content'])
        sliceTotal = int(itemLength / 1000) + 1
        for i in range(sliceTotal):
            start = i * 1000
            end = start + 1100
            if end > itemLength:
                end = itemLength
            sliceContent = info['content'][start:end]
            createBody = {"index": {"_index": 'personal_documents'}}
            iteminfo = {
                "content": sliceContent,
                "user_id": info['user_id'],
                "osskey": info['osskey'],
                "filename": info['filename'],
                "delete": info['delete'],
                "slice": i
            }
            body.append(createBody)
            body.append(iteminfo)
        try:
            self.es.bulk(body=body, index='personal_documents', refresh=True, request_timeout=200)
        except Exception as e:
            print(e)


if __name__ == '__main__':
    bot = DocumentEs()

    bot.createLocalIndex()

